﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TMaterialWikiRepository : BaseRepository<TMaterialWiki>, ITMaterialWikiRepository
    {
        public TMaterialWikiRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 添加物料知识库
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTMaterialWiki(TMaterialWiki m)
        {
            //使用事务的原子性
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    #region 添加物料知识库
                    var mobj = Context.TMaterials.Find(m.MaterialId);
                    if (mobj != null)
                    {
                        m.MaterialName = mobj.Name;
                        m.MaterialCode = mobj.Code;
                    }
                    m.CreateUserId = m.NowUserId;
                    m.CreateUserName = m.NowUserRealName;
                    m.CreateDate = DateTime.Now;
                    m.ModifyDate = DateTime.Now;
                    m.ModifyUserName = m.NowUserRealName;
                    m.ModifyUserId = m.NowUserId;
                    Context.TMaterialWikis.Add(m);
                    Context.SaveChanges();
                    #endregion

                    #region 添加附件
                    foreach (var item in m.FileModels)
                    {
                        Guid guid = Guid.NewGuid();
                        item.MaterialWikiId = m.Id;
                        item.FileUrl = @"\Files\MaterialWiki\"+guid+item.Suffix;
                        item.CreateUserId = m.NowUserId;
                        item.CreateUserName=m.NowUserRealName;
                        item.CreateDate = DateTime.Now;
                        Context.TMaterialWikiFiles.Add(item);
                        Context.SaveChanges();
                    }
                    #endregion                   
                    //提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 删除物料知识库
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelTMaterialWiki(int mid)
        {
            var mobj = Context.TMaterialWikis.Find(mid);
            if(mobj!=null)
            {
                Context.TMaterialWikis.Remove(mobj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 根据Id获取对象信息
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TMaterialWiki GetTMaterialWikiById(int mid)
        {
            var m = Context.TMaterialWikis.Find(mid);
            var mw = Context.TMaterialWikiFiles.Where(x=>x.MaterialWikiId==mid);
            m.FileModels = mw.Select(x => new TMaterialWikiFile
            {
                Id= x.Id,
                MaterialWikiId=x.MaterialWikiId,
                FileUrl=x.FileUrl,
                FileName=x.FileName,
                FileType=x.FileType,
                Suffix=x.Suffix,
                Remark=x.Remark,
                CreateUserId=x.CreateUserId,
                CreateUserName=x.CreateUserName,
            }).ToList();
            return m;
        }

        /// <summary>
        /// 显示物料知识库列表
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<TMaterialWiki> GetTMaterialWikiList(string mname, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TMaterialWikis.AsNoTracking().AsQueryable();

            if(!string.IsNullOrEmpty(mname))
            {
                list = list.Where(x => x.MaterialName.Contains(mname));
            }

            totalCount=list.Count();

            return list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 修改物料知识库
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdTMaterialWiki(TMaterialWiki m)
        {
            //使用事务的原子性
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    #region 修改物料知识库
                    var mobj = Context.TMaterials.Find(m.MaterialId);
                    if (mobj != null)
                    {
                        m.MaterialName = mobj.Name;
                        m.MaterialCode = mobj.Code;
                    }
                    m.ModifyDate = DateTime.Now;
                    m.ModifyUserName = m.NowUserRealName;
                    m.ModifyUserId = m.NowUserId;
                    Context.TMaterialWikis.Update(m);
                    Context.SaveChanges();
                    #endregion

                    #region 删除已有的附件
                    var wmlist = Context.TMaterialWikiFiles.Where(x => x.MaterialWikiId == m.Id);
                    if (wmlist.Any()) 
                    {
                        Context.TMaterialWikiFiles.RemoveRange(wmlist);
                        Context.SaveChanges();
                    }
                    #endregion

                    #region 添加附件
                    foreach (var item in m.FileModels)
                    {
                        item.Id = 0;
                        Guid guid = Guid.NewGuid();
                        item.MaterialWikiId = m.Id;
                        item.FileUrl = @"\Files\MaterialWiki\" + guid + item.Suffix;
                        item.CreateUserId = m.NowUserId;
                        item.CreateUserName = m.NowUserRealName;
                        item.CreateDate = DateTime.Now;
                        Context.TMaterialWikiFiles.Add(item);
                        Context.SaveChanges();
                    }
                    #endregion              
                    //提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }
    }
}
